﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Entity;

namespace School.WebPages.Message
{
    public partial class MessageList : BasePage
    {
        TechnologySchoolEntities db = new TechnologySchoolEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int total = db.MessageBoard.Where(m => m.IsChecked == true).Count();
                AspNetPager1.RecordCount = total;
                BindData();
            }
        }

        private void BindData()
        {
            rep_message.DataSource = DAL.PagerHelper.GetPagerData("MessageBoard", "Question,ClientName,QTime,Answer", "QTime", 
                AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, "IsChecked=1");
            rep_message.DataBind();          
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
        {

            if (txbCode.Text.ToUpper() != GetCookie("CheckCode"))
            {
                lblMsg.Text = "提交失败，验证码错误！";
                return;
            }

            try
            {
                MessageBoard message = new MessageBoard();

                message.Question = HttpUtility.HtmlEncode(txbMessage.Text.Trim());
                message.ClientName = txbClientName.Text.Trim();
                message.QTime = DateTime.Now;
                message.IsChecked = false;

                db.AddToMessageBoard(message);
                if (db.SaveChanges() > 0)
                {
                    BindData();
                    lblMsg.Text = "您的留言已成功提交，等待管理员审核。";
                }
                else
                {
                    lblMsg.Text = "提交失败。";
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "提交发生异常,原因：" + ex.Message;
            }
        }

        protected void rep_message_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord)e.Item.DataItem;
            string answer = record["Answer"].ToString();
            if (answer.Trim().Length == 0 || answer.Trim() == string.Empty)
            {
                e.Item.FindControl("answerContainer").Visible = false;
            }
        }
    }
}
